package com.example.test.nettytest.netty;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

@Sharable
public class HeartBeatClientHandler extends SimpleChannelInboundHandler {
    private static Logger log = LoggerFactory.getLogger(HeartBeatClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("激活时间是：" + new Date());
        log.info("HeartBeatClientHandler channelActive");
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("停止时间是：" + new Date());
        log.info("HeartBeatClientHandler channelInactive");
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object o) throws Exception {
        ByteBuf buf = (ByteBuf) o;
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        log.info("|Accepts|" + CRC16M.getBufHexStr(data));
        int head = data[0]&0xff;
        if(head == 255){
            log.info("接收到服务器心跳数据:"+head);
        }else{
            log.info("接收到其他数据：head:"+head);
            int length = FormatTransfer.hBytesToShort(FormatTransfer.copy(data, 4, 2));// 消息长度
            int type = (int)data[7];
            if(type == 3){
                log.info("服务器查询消息："+length);

                String q = "AA0600C800CC"+"0103"+"00020002000200010003001200000000000000000000"+"FFEEAAAA"+"0000AAFF"+"00000000000000000000"
                                                +"00010002000100010001001600000000000000000000"+"FFE000AA"+"00BBAAFF"+"00000000000000000000"
                                                +"00020003000300000002001600000000000000000000"+"0FEEAAAA"+"FEA0AAFF"+"00000000000000000000"
                                                +"00020001000100010001001500000000000000000000"+"0FEEAAAA"+"FEA0AAFF"+"00000000000000000000"
                                                +"00020003000200000003001300000000000000000000"+"0FEEAAAA"+"FEA0AAFF"+"00000000000000000000";
                byte[] sbuf = CRC16M.getSendBuf(q);
                log.info("---："+sbuf.length);
                ctx.writeAndFlush(sbuf);
            }else if(type == 6){
                log.info("控制消息："+length);
                ctx.writeAndFlush(data);
            }else{
                log.info("指令无效");
            }
        }
    }


}